package com.jindy.module.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.jindy.common.constant.Constants;
import com.jindy.common.core.domain.AjaxResult;
import com.jindy.common.core.domain.entity.SysDept;
import com.jindy.common.core.domain.entity.SysRole;
import com.jindy.common.core.domain.entity.SysUser;
import com.jindy.common.core.domain.model.LoginUser;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.jpush.domain.UniPushDomain;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalConfig.domain.ApprovalConfig;
import com.jindy.module.approvalConfig.mapper.ApprovalConfigMapper;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.constant.StatusConstants;
import com.jindy.module.copy.domain.Copy;
import com.jindy.module.copy.mapper.CopyMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.logisticscost.domain.LogisticsCost;
import com.jindy.module.logisticscost.mapper.LogisticsCostMapper;
import com.jindy.module.machine.dto.MachineDto;
import com.jindy.module.order.domain.Order;
import com.jindy.module.order.domain.OrderApprovalResult;
import com.jindy.module.order.domain.OrderProduct;
import com.jindy.module.order.mapper.OrderMapper;
import com.jindy.module.order.mapper.OrderProductMapper;
import com.jindy.module.order.service.IOrderService;
import com.jindy.module.product.domain.Product;
import com.jindy.module.product.mapper.ProductMapper;
import com.jindy.module.warehouse.domain.Warehouse;
import com.jindy.module.warehouse.service.IWarehouseService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import com.jindy.ws.po.Message;
import com.jindy.ws.service.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.jindy.common.constant.Constants.WU_LIU_DEPT_ID;
import static com.jindy.common.utils.PageUtils.startPage;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-08
 */
@Service
public class OrderServiceImpl implements IOrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    private OrderMapper orderMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderProductMapper orderProductMapper;
    @Resource
    private LogisticsCostMapper logisticsCostMapper;

    /**
     * 查询人员信息
     */
    @Resource
    private ISysUserService userService;

    /**
     * 审批记录
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 审批配置表
     */
    @Resource
    private ApprovalConfigMapper approvalConfigMapper;

    /**
     * 抄送记录
     */
    @Resource
    private CopyMapper copyMapper;

    /**
     * 消息推送设备信息表
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 消息推送Server
     */
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     *仓库信息
     */
    @Resource
    private IWarehouseService warehouseService;


    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        Order order = orderMapper.selectOrderById(id);
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setOrderId(id);
        List<OrderProduct> productList = orderProductMapper.selectOrderProductList(orderProduct);
        order.setProductList(productList);

        LogisticsCost logisticsCost = new LogisticsCost();
        logisticsCost.setOrderId(id);
        List<LogisticsCost> logisticsCostList = logisticsCostMapper.selectLogisticsCostList(logisticsCost);
        order.setLogisticsCostList(logisticsCostList);

        return order;
    }

    /**
     * 查询订单列表
     *
     * @param order  订单
     * @return 订单
     */
    @Override
    public List<OrderApprovalResult> selectOrderList(Order order) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser)){
            throw new BaseException("selectOrderList","获取用户登录信息异常");
        }
        List<ApprovalConfig> marketDeptList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("SCB", "1"));
        if (CollectionUtils.isEmpty(marketDeptList)){
            throw new BaseException("selectOrderList","获取市场部id异常");
        }
        //获取所有用户职位，角色，领导信息
        List<SysUserRoleDeptInfo> sysUserList = userService.selectAllUsers();
        //判断登录人是否归属市场部
        boolean isMarketDept = isMarketDept(sysUserList, loginUser,marketDeptList);
        //数据权限设置：
        // 1.周总可以看所有数据
        if ("周德友".equals(loginUser.getUser().getUserName())){
            order.setUserId(1L);
        }else if(isMarketDept){
            //获取市场部渠道经理名单,判断是否为渠道经理
            List<SysUserRoleDeptInfo> managerIdList =
                    sysUserList.stream()
                            .filter(sysUserRoleDeptInfo -> "渠道经理".equals(sysUserRoleDeptInfo.getRoleName()) && "市场部".equals(sysUserRoleDeptInfo.getDeptName()))
                            .filter(sysUserRoleDeptInfo -> loginUser.getUserId().equals(sysUserRoleDeptInfo.getUserId()))
                            .distinct()
                            .collect(Collectors.toList());
            LOGGER.info("是否是渠道经理："+managerIdList.size());
            if (!CollectionUtils.isEmpty(managerIdList)){
                // 2. 市场部的渠道经理可以查看管理下的渠道业务员和合伙人
                List<Long> subUserIdList = new ArrayList<>();
                for (SysUserRoleDeptInfo sysUserRoleDeptInfo : sysUserList) {
                    if (loginUser.getUserId().equals(sysUserRoleDeptInfo.getLeaderId())){
                        subUserIdList.add(sysUserRoleDeptInfo.getUserId());
                    }
                }
                LOGGER.info("渠道业务员及合伙人："+subUserIdList.size());
                subUserIdList.add(loginUser.getUserId());
                order.setUserIdList(subUserIdList.stream().distinct().collect(Collectors.toList()));
            }else{
                //市场部其他人看自己订单
                order.setUserId(loginUser.getUserId());
            }
        }
        startPage();
        List<OrderApprovalResult> list = orderMapper.selectOrderApprovalList(order);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(or -> {
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.setOrderId(or.getId());
                List<OrderProduct> productList = orderProductMapper.selectOrderProductList(orderProduct);
                or.setProductList(productList);

                LogisticsCost logisticsCost = new LogisticsCost();
                logisticsCost.setOrderId(or.getId());
                List<LogisticsCost> logisticsCostList = logisticsCostMapper.selectLogisticsCostList(logisticsCost);
                or.setLogisticsCostList(logisticsCostList);
            });
        }
        return list;
    }

    /**
     * 判断登录人是否归属市场部
     * @param sysUserList
     * @param loginUser
     * @return
     */
    private boolean isMarketDept(List<SysUserRoleDeptInfo> sysUserList, LoginUser loginUser,List<ApprovalConfig> marketDeptList) {
        if (loginUser.getDeptId().equals(marketDeptList.get(0).getUserId())){
            return true;
        }
        for (SysUserRoleDeptInfo sysUserRoleDeptInfo : sysUserList) {
            if (sysUserRoleDeptInfo.getUserId().equals(loginUser.getUserId())){
                if (sysUserRoleDeptInfo.getAncestors().contains(marketDeptList.get(0).getExtra())){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<Order> selectOrderListByMachineId(MachineDto machineDto) {
        return orderMapper.selectOrderListByMachineId(machineDto);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertOrder(Order order) {
        // 获取当前人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("请先登录");
        }
        // 判断是否再提交
        if (null==order.getId()){
            // 新增订单
            addOrder(order);
            // 新增订单产品
            insertOrderProducts(order);
            // 新增物流费用列表
//            insertLogisticsCost(order);
        }else{
            // 再提交
            order.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            order.setUpdateBy(loginUser.getUsername());
            updateOrder(order);
            //删除审批记录
            approvalRecordMapper.deleteApprovalRecordBySerialNum(order.getOrderNo());
            // 删除抄送
            copyMapper.deleteCopyMapperBySerialNum(order.getOrderNo());
        }
        // 新增审批记录
        List<Long> addJpushList= addApprovalRecord(order, loginUser);
        // 新增抄送记录
        List<Long> jpushCopyList = addCopyRecord(order, loginUser);

        sendApproveMessage(addJpushList);

        sendCopyMessage(jpushCopyList);
        // 内部消息推送
        sendMessage(addJpushList.get(0),order);
    }

    /**
     * 给抄送人推送消息
     * @param jpushCopyList
     */
    private void sendCopyMessage(List<Long> jpushCopyList) {
        try {
            List<String> copyRegIds = jpushMapper.selectRegistrationIdsByUserIds(jpushCopyList);
            if (!CollectionUtils.isEmpty(copyRegIds)){
                UniJpushUtils.sendCopyMessage(copyRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("租赁订单抄送人推送通知失败",e);
        }
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("租赁订单审批人推送通知失败",e);
        }
    }

    /**
     * 推送消息到前端
     * @param userId
     * @param order
     */
    private void sendMessage(Long userId, Order order) {
        try {
            //发送消息
            Message message = new Message();
            message.setFromId(order.getSponsor());
            message.setFromName(order.getSponsorName());
            message.setNextNodeId(userId);
            message.setSerialNum(order.getOrderNo());
            webSocketServer.onMessage(JSON.toJSONString(message));
        } catch (Exception e) {
            LOGGER.error("租赁订单内部消息推送失败",e);
        }
    }

    /**
     * 新增抄送记录
     *
     * @param order
     * @param loginUser
     */
    private List<Long> addCopyRecord(Order order, LoginUser loginUser) {
        //  获取抄送人
        List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_COPYER", "1"));
        LOGGER.info("获取抄送人人数"+approvalConfigList.size());
        if (!CollectionUtils.isEmpty(approvalConfigList)) {
            for (ApprovalConfig approvalConfig : approvalConfigList) {
                Copy copyRecord = getCopyRecord(order, loginUser);
                copyRecord.setCopyerId(approvalConfig.getUserId());
                copyRecord.setCopyerName(approvalConfig.getUsername());
                copyMapper.insertCopy(copyRecord);
            }
        }
        return approvalConfigList.stream().map(approvalConfig -> approvalConfig.getUserId()).collect(Collectors.toList());
    }

    /**
     * 获取抄送记录对象
     *
     * @param order
     * @param loginUser
     */
    private Copy getCopyRecord(Order order, LoginUser loginUser) {
        Copy copyRecord = new Copy();
        copyRecord.setSerialNum(order.getOrderNo());
        copyRecord.setUserId(order.getSponsor());
        copyRecord.setCopyerStatus("0");
        copyRecord.setOrderId(order.getId());
        copyRecord.setUsername(order.getSponsorName());
        copyRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        copyRecord.setUpdateBy(loginUser.getUsername());
        copyRecord.setCreateBy(loginUser.getUsername());
        copyRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        copyRecord.setProjectName(order.getProjectName());
        return copyRecord;
    }

    /**
     * 新增审批记录
     *
     * @param order
     * @param loginUser
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> addApprovalRecord(Order order, LoginUser loginUser) {
        try {
            if ("1".equals(order.getContractTemplate())){
                //订单类型为：租赁订单
                //区分是否内外部人员
                boolean isInternalEmployeeResult = isInternalEmployee(order);
                if (isInternalEmployeeResult) {
                    //  发起人是内部人员
                    return insertInternalApprovalRecord(order, loginUser);
                } else {
                    //  发起人是外部人员
                    return insertOutsideApprovalRecord(order, loginUser);
                }
            }else{
                //订单类型为：销售订单
                return insertSaleApprovalRecord(order, loginUser);
            }

        } catch (Exception e) {
            LOGGER.error("新增审批记录失败",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 销售订单审批
     * @param order
     * @param loginUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> insertSaleApprovalRecord(Order order, LoginUser loginUser) {
        //消息推送人员
        List<Long> jpushList = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(order, loginUser);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(order.getSponsor());
        firstApprovalRecord.setApproverName(order.getSponsorName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);


        sequence++;
        //  周总
        List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_XS_LEADER", "1"));
        if (CollectionUtils.isEmpty(approvalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_XS_LEADER");
        }
        addApprovalConfig(sequence, approvalConfigList,order, loginUser);
        jpushList.add(approvalConfigList.get(0).getUserId());

        sequence++;
        //  范雯雯
        List<ApprovalConfig> thirdApprovalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_XS_CN", "1"));
        if (CollectionUtils.isEmpty(thirdApprovalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_XS_CN");
        }
        addApprovalConfig(sequence, thirdApprovalConfigList,order, loginUser);

        //物流
        sequence++;
        List<SysUser> wlList = userService.selectUserByDeptId(WU_LIU_DEPT_ID);
        if (CollectionUtils.isEmpty(wlList)){
            throw new BaseException("物流人员信息空");
        }
        for (SysUser sysUser : wlList) {
            ApprovalRecord kfApprovalRecord = getApprovalRecord(order, loginUser);
            kfApprovalRecord.setSequence(sequence);
            kfApprovalRecord.setApprovalStatus(Constants.NOT_APPROVED);
            kfApprovalRecord.setApproverId(sysUser.getUserId());
            kfApprovalRecord.setApproverName(sysUser.getUserName());
            kfApprovalRecord.setRole("物流");
            approvalRecordMapper.insertApprovalRecord(kfApprovalRecord);
        }
        return jpushList;
    }

    /**
     * 发起人是外部人员 流程记录
     *
     * @param order
     * @param loginUser
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> insertOutsideApprovalRecord(Order order, LoginUser loginUser) {
        //消息推送人员
        List<Long> jpushList = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(order, loginUser);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(order.getSponsor());
        firstApprovalRecord.setApproverName(order.getSponsorName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  第二审批人：渠道经理
        SysUser sysUser = userService.selectUserById(order.getSponsor());
        if (sysUser == null) {
            throw new RuntimeException("发起人信息错误");
        }
        SysDept dept = sysUser.getDept();
        if (dept == null) {
            throw new RuntimeException("发起人渠道经理职位信息为空");
        }
        ApprovalRecord approvalRecord = getApprovalRecord(order,loginUser);
        approvalRecord.setSequence(sequence);
        approvalRecord.setApprovalStatus(Constants.APPROVE);
        approvalRecord.setApproverId(dept.getLeaderId());
        approvalRecord.setApproverName(dept.getLeader());
        approvalRecordMapper.insertApprovalRecord(approvalRecord);
        jpushList.add(dept.getLeaderId());

        sequence++;
        //  第三审批人：默认周总
        List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_NB_LEADER", "1"));
        if (CollectionUtils.isEmpty(approvalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_NB_LEADER");
        }
        addApprovalConfig(sequence, approvalConfigList,order, loginUser);

        sequence++;
        //  第四审批人出纳：默认范雯雯
        List<ApprovalConfig> thirdApprovalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_CN", "1"));
        if (CollectionUtils.isEmpty(thirdApprovalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_CN");
        }
        addApprovalConfig(sequence, thirdApprovalConfigList,order, loginUser);
        return jpushList;
    }

    /**
     * 发起人是内部人员 流程记录
     *
     * @param order
     * @param loginUser
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> insertInternalApprovalRecord(Order order, LoginUser loginUser) {

        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(order, loginUser);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(order.getSponsor());
        firstApprovalRecord.setApproverName(order.getSponsorName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  第二审批人：默认周总
        List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_NB_LEADER", "1"));
        if (CollectionUtils.isEmpty(approvalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_NB_LEADER");
        }
        addApprovalConfig(sequence, approvalConfigList,order, loginUser);

        sequence++;
        //  第三审批人出纳：默认范雯雯
        List<ApprovalConfig> thirdApprovalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("ZLDD_CN", "1"));
        if (CollectionUtils.isEmpty(thirdApprovalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：ZLDD_CN");
        }
        addApprovalConfig(sequence, thirdApprovalConfigList,order, loginUser);

        return approvalConfigList.stream().map(approvalConfig -> approvalConfig.getUserId()).collect(Collectors.toList());
    }

    /**
     * 新增第二，第三审批记录信息
     *
     * @param sequence
     * @param approvalConfigList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addApprovalConfig(int sequence, List<ApprovalConfig> approvalConfigList,Order order, LoginUser loginUser) {
        String status = Constants.NOT_APPROVED;
        if (sequence == 2) {
            status = Constants.APPROVE;
        }
        for (ApprovalConfig approvalConfig : approvalConfigList) {
            ApprovalRecord approvalRecord = getApprovalRecord(order,loginUser);
            approvalRecord.setSequence(sequence);
            approvalRecord.setApprovalStatus(status);
            approvalRecord.setApproverId(approvalConfig.getUserId());
            approvalRecord.setApproverName(approvalConfig.getUsername());
            approvalRecordMapper.insertApprovalRecord(approvalRecord);
        }
    }

    /**
     * 获取审批记录对象
     *
     * @param order
     * @param loginUser
     * @return
     */
    private ApprovalRecord getApprovalRecord(Order order, LoginUser loginUser) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(order.getOrderNo());
        approvalRecord.setUserId(order.getSponsor());
        approvalRecord.setOrderId(order.getId());
        approvalRecord.setProjectName(order.getProjectName());
        approvalRecord.setUserName(order.getSponsorName());
        approvalRecord.setCreateBy(loginUser.getUsername());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 判断发起人是否是内部人员
     *
     * @param order
     */
    public boolean isInternalEmployee(Order order) {
        //  发起人是内部内部人员
        if (order == null) {
            throw new RuntimeException("订单信息为空");
        }
        SysUser sysUser = userService.selectUserById(order.getSponsor());
        if (sysUser == null) {
            throw new RuntimeException("发起人信息错误");
        }
        List<SysRole> roleList = sysUser.getRoles();
        if (CollectionUtils.isEmpty(roleList)) {
            throw new RuntimeException("请配置" + order.getSponsorName() + "角色信息");
        }
        List<SysRole> roles = roleList.stream().filter(sysRole -> "渠道业务员".equals(sysRole.getRoleName()) || "合伙人".equals(sysRole.getRoleName())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(roles)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 新增订单消息
     *
     * @param order
     */
    public void addOrder(Order order) {
        try {
            SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
            order.setCreateBy(sysUser.getUserName());
            order.setCreateTime(DateUtils.getNowDate());
            order.setSponsor(sysUser.getUserId());
            order.setSponsorName(sysUser.getUserName());
            order.setSponsorDept(sysUser.getDeptId());
            order.setSponsorDeptName(sysUser.getDept().getDeptName());
            order.setShipmentStatus(StatusConstants.ShipmentStatusConstant.shipmentStatus_2);// 待发货
            order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_0);// 未审批
            order.setDeliveryStatus(StatusConstants.DeliveryStatusConstant.deliveryStatus_1);// 待出库
            orderMapper.insertOrder(order);
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl新增订单消息", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增订单产品
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderProducts(Order order) {
        try {
            if (order != null) {
                if (!CollectionUtils.isEmpty(order.getProductList())) {
                    // 关联产品
                    order.getProductList().forEach(orderProduct -> {
                        // 查询产品其他信息
                        Product product = productMapper.selectProductById(orderProduct.getProductId());
                        orderProduct.setUnit(product.getUnit());
                        orderProduct.setOrderId(order.getId());
                        orderProduct.setUndeliveryQuantity(orderProduct.getQuantity());
                        LOGGER.info("未出库数量" + orderProduct.getQuantity());
                    });
                    orderProductMapper.insertOrderProducts(order.getProductList());
                }
            }
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl新增订单产品失败", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增物流费用列表
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertLogisticsCost(Order order) {
        try {
            if (order != null) {
                // 插入物流费用列表
                if (!CollectionUtils.isEmpty(order.getLogisticsCostList())) {
                    order.getLogisticsCostList().forEach(logisticsCost -> {
                        logisticsCost.setOrderId(order.getId());
                        logisticsCost.setProjectName(order.getOrderNo());
                        logisticsCost.setProjectName(order.getProjectName());
                        logisticsCostMapper.insertLogisticsCost(logisticsCost);
                    });
                }
            }
        } catch (Exception e) {
            LOGGER.error("OrderServiceImpl新增物流费用列表", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {


        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        order.setUpdateBy(sysUser.getUserName());
        order.setUpdateTime(DateUtils.getNowDate());

        if(order.getOrderStatus().equals(StatusConstants.OrderStatusConstant.orderStatus_0) || order.getOrderStatus().equals(StatusConstants.OrderStatusConstant.orderStatus_13)){ // 删除订单关联的产品
            orderProductMapper.deleteOrderProductByOrderId(order.getId());

            if (!CollectionUtils.isEmpty(order.getProductList())) {
                // 关联产品
                order.getProductList().forEach(orderProduct -> {

                    // 查询产品其他信息
                    Product product = productMapper.selectProductById(orderProduct.getProductId());
                    orderProduct.setUnit(product.getUnit());
                    orderProduct.setOrderId(order.getId());
                    orderProduct.setUndeliveryQuantity(orderProduct.getQuantity());
                    orderProductMapper.insertOrderProduct(orderProduct);
                });
            }


//                Integer quantity = orderProductMapper.getQuantityCount(order.getId());
//                Integer undeliveryQuantity = orderProductMapper.getUndeliveryQuantityCount(order.getId());

//                if (quantity < orderProduct.getQuantity()) {
                    // 修改出库状态
//                    order.setDeliveryStatus(StatusConstants.DeliveryStatusConstant.deliveryStatus_1);// 待出库
                    // 追加订单后未出库数量
//                    Long undelivery = undeliveryQuantity + orderProduct.getQuantity() - quantity;
//                    orderProduct.setUndeliveryQuantity(undelivery);
//                    orderProductMapper.updateOrderProduct(orderProduct);
//
//                    OutboundOrder outboundOrder1 = new OutboundOrder();
//                    outboundOrder1.setOrderId(orderProduct.getOrderId());
//                    List<OutboundOrder> outboundOrderList = outboundOrderMapper.selectOutboundOrderList(outboundOrder1);
//                    outboundOrderList.forEach(outboundOrder -> {
//                        if (outboundOrder.getParentId().equals(0L)) {
//                            // 修改出库申请单父单为未出库，修改父单未出库数量。
//                            outboundOrder.setOrderStatus(StatusConstants.DeliveryStatusConstant.deliveryStatus_1);
//                            outboundOrder.setUndeliveryQuantity(undelivery.intValue());
//                            outboundOrderMapper.updateOutboundOrder(outboundOrder);
//                        } else {
//                            // 追加订单后，每个子订单出库数量
//                            Long undeliveryQuantity1 = outboundOrder.getUndeliveryQuantity() + undelivery;
//                            outboundOrder.setUndeliveryQuantity(undeliveryQuantity1.intValue());
//                            outboundOrderMapper.updateOutboundOrder(outboundOrder);
//                        }
//                    });
//                    // 将订单状态改为执行中
//                    order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_1);
//                    orderMapper.updateOrder(order);
//                    // 将回库申请单父状态改为已提交
//                    ReturnApplyDto returnApply1 = new ReturnApplyDto();
//                    returnApply1.setOrderId(orderProduct.getOrderId());
//                    returnApply1.setParentId(0L);
//                    List<ReturnApplyDto> returnApplyList = returnApplyMapper.selectReturnApplyList(returnApply1);
//                    returnApplyList.forEach(returnApply -> {
//                        returnApply.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_1);
//                        returnApplyMapper.updateReturnApply(returnApply);
//                    });

//                }

//            orderProductMapper.insertOrderProducts(order.getProductList());
        }


//        logisticsCostMapper.deleteLogisticsCostByOrderId(order.getId());
//        // 插入物流费用列表
//        if (!CollectionUtils.isEmpty(order.getLogisticsCostList())) {
//            order.getLogisticsCostList().forEach(logisticsCost -> {
//                logisticsCost.setOrderId(order.getId());
//                logisticsCost.setOrderNo(order.getOrderNo());
//                logisticsCost.setProjectName(order.getProjectName());
//                logisticsCostMapper.insertLogisticsCost(logisticsCost);
//            });
//        }

        return orderMapper.updateOrder(order);
    }

    /**
     * 修改订单状态
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateStatus(Order order) {
        order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_1);
        return orderMapper.updateOrder(order);
    }


    /**
     * 修改订单状态（0->11)
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateStatus2(Order order) {
        order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_11);
        return orderMapper.updateOrder(order);
    }

    /**
     * 修改订单状态(0->8)
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateStatus1(Order order) {
        order.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_8);
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }

    /**
     * 提示仓管员
     * @param orderNo
     */
    public void noticeStorekeeper(String orderNo){
        try {
            Order order = orderMapper.selectOrderByOrderNo(orderNo);
            LOGGER.info("提示仓管员order是否为空："+Objects.nonNull(order));
            if (Objects.nonNull(order)){
                //获取仓库
                String deliveryWarehouseName = order.getDeliveryWarehouseName().trim();
                LOGGER.info("仓库名称"+deliveryWarehouseName);
                // 获取仓库信息
                Warehouse warehouse = new Warehouse();
                warehouse.setWarehouseName(deliveryWarehouseName);
                List<Warehouse> warehouses = warehouseService.selectWarehouseList(warehouse);
                LOGGER.info("获取仓库名称："+warehouses.size());
                if (CollectionUtils.isEmpty(warehouses)){
                    throw new BaseException("根据仓库名获取仓库信息失败");
                }
                List<Long> responsibleUserList = warehouses.stream().map(warehouse1 -> Long.parseLong(warehouse1.getResponsibleUser())).collect(Collectors.toList());
                List<String> regid = jpushMapper.selectRegistrationIdsByUserIds(responsibleUserList);
                if (!CollectionUtils.isEmpty(regid)){
                    LOGGER.info("通知仓管："+regid.size());
                    UniJpushUtils.doPost(new UniPushDomain(regid,"湿云","仓管人员你好！"+orderNo+"已审批完"));
                }else{
                    throw new BaseException("获取仓管设备id失败");
                }
            }
        } catch (Exception e) {
            LOGGER.error("通知仓管失败：",e);
        }
    }

    /**
     * 查询租赁订单
     * @param numberList 订单编号 集合
     * @return
     */
    @Override
    public List<Order> findOrdersByNumbers(List<String> numberList) {
        return orderMapper.selectOrderListByNumbers(numberList);
    }

    /**
     * 对账单预警通知业务员
     * @return
     */
    @Override
    public AjaxResult statementWarningTimer() {
        List<OrderApprovalResult> orderApprovalResults = orderMapper.selectOrderApprovalList(new Order());
        if (CollectionUtils.isEmpty(orderApprovalResults)){
            return AjaxResult.success("对账单预警通知业务员-查询订单为空");
        }
        List<OrderApprovalResult> collect = orderApprovalResults.stream().filter(a -> a.getWarehouseTime() != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return AjaxResult.success("无入库完成数据");
        }
        List<Long> userList = new ArrayList<>();
        for (OrderApprovalResult orderApprovalResult : collect) {
        //    计算当前时间和入库完成时间差值
            Date warehouseTime = orderApprovalResult.getWarehouseTime();
            LocalDate warehouseDate = warehouseTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate now = LocalDate.now();
            long days = warehouseDate.until(now, ChronoUnit.DAYS);
            if (13==days){
                userList.add(orderApprovalResult.getSalesman());
            }
            if (15==days){
                userList.add(orderApprovalResult.getSalesman());
            }
        }
        LOGGER.error("对账单预警通知业务员人数", userList.size());
        if (!CollectionUtils.isEmpty(userList)){
            noticeInitiator(userList);
        }
        return AjaxResult.success();
    }

    /**
     * 通知业务员
     *
     * @param userIdList
     */
    private void noticeInitiator(List<Long> userIdList) {
        try {
            List<String> userIds = jpushMapper.selectRegistrationIdsByUserIds(userIdList);
            if (!CollectionUtils.isEmpty(userIds)){
                UniJpushUtils.doPost(new UniPushDomain(userIds, "湿云", "对账单预警通知业务员"));
            }
        } catch (Exception e) {
            LOGGER.error("对账单预警通知业务员-失败", e);
        }
    }

}
